package com.jcli.properties_乱码;


import org.apache.commons.configuration2.PropertiesConfiguration.PropertiesWriter;
import org.apache.commons.configuration2.convert.ListDelimiterHandler;
import org.apache.commons.configuration2.convert.ValueTransformer;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

/**
 * 实现properties文件中unicode字符不转义(escape)直接输出
 * 加依赖
 */
public class MyPropertiesWriter extends PropertiesWriter {
    // 自定义实现的ValueTransformer,直接返回String,没有escape过程
    private final ValueTransformer TRANSFORMER = new ValueTransformer(){

        @Override
        public Object transformValue(Object value) {
            return String.valueOf(value);
        }
    };

    /**
     *  代码从父类方法中原样复制没有改变,主要是为调用自定义的TRANSFORMER
     * @param key
     * @param value
     * @param forceSingleLine
     * @throws IOException
     */
    @Override
    public void writeProperty(String key, Object value, boolean forceSingleLine) throws IOException {
        String v;

        if (value instanceof List)
        {
            v = null;
            List<?> values = (List<?>) value;
            if (forceSingleLine)
            {
                try
                {
                    v = String.valueOf(getDelimiterHandler()
                            .escapeList(values, TRANSFORMER));
                }
                catch (UnsupportedOperationException uoex)
                {
                    // the handler may not support escaping lists,
                    // then the list is written in multiple lines
                }
            }
            if (v == null)
            {
                writeProperty(key, values);
                return;
            }
        }
        else
        {
            v = String.valueOf(getDelimiterHandler().escape(value, TRANSFORMER));
        }

        write(escapeKey(key));
        write(fetchSeparator(key, value));
        write(v);

        writeln(null);
    }


    public MyPropertiesWriter(Writer writer, ListDelimiterHandler delHandler) {
        super(writer, delHandler);
    }
}
